package com.fuze.interceptor;

import com.fuze.common.Advice;
import com.fuze.common.CustomException;
import com.fuze.common.constant.Constant;
import com.fuze.domain.model.Administrators;
import com.fuze.domain.model.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sepc_
 * @date 3/17/2021 09:32
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class TokenInterceptor implements HandlerInterceptor {


    public final RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestUri = request.getRequestURI();
        log.info("requestURI = {}", requestUri);
        // 获取头中token
        String token = request.getHeader(Constant.AUTH_TOKEN);
        log.info("token = {}", token);
        if (StringUtils.isBlank(token)) {
            // 如果是预检请求，错误可以忽略
            throw new CustomException(Advice.TOKEN_MISSING);
        }
        Object o = redisTemplate.opsForValue().get(token);
        if (o == null) {
            // 取不到对象说明Token过期了
            throw new CustomException(Advice.TOKEN_EXPIRED);
        }
        // 判断是用户还是管理员，这里肯定为true，这里需要做的事保存用户的登录日志
        if (o instanceof User || o instanceof Administrators) {
            return true;
        }
        throw new CustomException(Advice.TOKEN_VERIFICATION_FAILED);
    }

}
